import React, { useState, useEffect } from 'react';
// import { connect } from 'dva';
import { Tree, Spin, Input, Icon, Tooltip, Modal, Empty, Button, message } from 'antd';
import { useBoolean } from '@umijs/hooks';
import { connect } from 'dva';
import PubSub from 'pubsub-js';
import request from '@/utils/request';
import ScrollBar from '@/components/ScrollBar';
import Catalog from './components/Catalog';
import EditStatusFlow from './components/EditStatusFlow';
import styles from './index.less';

// import remove from 'lodash/remove';

const { TreeNode } = Tree;
const { Search } = Input;

const namespace = 'flowConfig';

const eventName = 'flowConfig_tree';

function TreeMenu(props) {
  // 初始化加载loading
  const [loading, setLoading] = useState(false);
  // 组织树数据
  const [TreeData, setTreeData] = useState([]);
  // 选中点击的值
  const [selectedKeysArr, setSelectedKeysArr] = useState(['']);
  // 展示的树节点
  const [expandedKeys, setExpandedKeys] = useState([]);
  // 是否自动展开父节点
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  // 搜索
  const [searchValue, setSearchValue] = useState('');
  // 编辑、新增目录模态框显示隐藏、编辑新增状态
  const [catalogVisiable, setcatalogVisiable] = useState(false);
  const [catalogStatus, setCatalogStatus] = useState('');
  const [catalogPassData, setCatalogPassData] = useState({});

  // 新增目录或者流程包的模态框
  const { state: flowStatus, setTrue: setTrueFlow, setFalse: setFalseFlow } = useBoolean(false);

  // 编辑状态机流程
  const [statusFlow, setStatusFlow] = useState(false);
  const [statusFlowType, setStatusFlowType] = useState('');

  // 通过dva来传递选中节点的id,对右侧数据进行查找
  const savePassId = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/savePassId`,
      payload: params,
    });
  };

  // 初始化获取接口的Tree集合
  const queryTreeData = () => {
    setLoading(true);
    request('pmc/pms/PmPackageCatalogController/queryTree', {
      data: { catalogId: '' },
    })
      .then(res => {
        if (res.success) {
          let node = {};
          const arr = [];
          res.data.map(item => {
            node = item;
            arr.push(node);
          });
          setTreeData(arr);
        } else {
          message.error(res.errMessage);
        }
      })
      .always(() => setLoading(false));
  };

  // 初始化
  useEffect(() => {
    queryTreeData();
    return savePassId('x_0,0');
  }, []);

  useEffect(() => {
    // 监听订阅
    PubSub.subscribe(`${eventName}.update`, () => {
      queryTreeData();
    });
    return () => {
      PubSub.unsubscribe(`${eventName}`);
    };
  });

  const passId = id => {
    savePassId(id);
  };

  // 选中节点
  const selectTreeNode = selectedKeys => {
    /* eslint-disable */
    selectedKeys.length > 0
      ? setSelectedKeysArr(selectedKeys)
      : setSelectedKeysArr(selectedKeysArr);
    /* eslint-enable */
    passId(selectedKeys.length > 0 ? selectedKeys.toString() : selectedKeysArr.toString());
  };

  // 编辑节点
  const edit = (event, item) => {
    if (item.leaf === true) {
      setStatusFlow(true);
      setCatalogPassData(item);
      setStatusFlowType('edit');
    } else {
      setcatalogVisiable(true);
      setCatalogStatus('edit');
      setCatalogPassData(item);
    }
  };

  // 删除节点
  const removeTree = (event, item) => {
    // event.stopPropagation();
    // event.nativeEvent.stopImmediatePropagation();
    Modal.confirm({
      content: `确认删除【${item.name}】？`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        setSelectedKeysArr(['']);
        // 删除状态机目录
        if (item.processType === '1100' && item.leaf === false) {
          request('pmc/pms/PmPackageCatalogController/delete', {
            method: 'GET',
            data: {
              catalogId: item.id,
            },
          }).then(res => {
            if (res.success) {
              message.success('删除成功！');
              queryTreeData();
              setSelectedKeysArr(['']);
              savePassId('x_0,0');
            } else {
              message.error('删除失败！');
            }
          });
        } else if (item.processType === '1100' && item.leaf === true) {
          // 删除状态机流程包
          request('pmc/pms/PmPackageController/delete', {
            method: 'GET',
            data: {
              packageId: item.id,
            },
          }).then(res => {
            if (res.success) {
              message.success('删除成功！');
              queryTreeData();
              setSelectedKeysArr(['']);
              savePassId('x_0,0');
            } else {
              message.error(res.errMessage);
            }
          });
        }
      },
    });
  };

  // 遍历递归集合数据，渲染组织树
  const renderTreeNode = TreeArr => {
    if (TreeArr && TreeArr.length > 0) {
      return TreeArr.map(item => {
        const index = item.name.indexOf(searchValue);
        const beforeStr = item.name.substr(0, index);
        const afterStr = item.name.substr(index + searchValue.length);
        let title = '';
        /**
         * 不同层级操作状态不同
         * 子节点：编辑、删除操作
         * 若父节点下无子节点数据  编辑、新增、删除
         * 若父节点下有子节点数据  编辑、新增
         * processType:1100 为状态机 1000 为 usoflow
         * 当前逻辑：后端默认返回usoflow与状态机两个父目录且不能进行删除操作与编辑操作
         * 1、usoflow 父目录跳转对应的iframe子系统
         */
        if (item.leaf) {
          title = (
            <span>
              {index > -1 ? (
                <span>
                  {beforeStr}
                  <span style={{ color: '#f50' }}>{searchValue}</span>
                  {afterStr}
                </span>
              ) : (
                <span>{item.name}</span>
              )}
              {item.processType === '1100' ? (
                <span className={styles.menu_tree_edit}>
                  <Tooltip title="编辑">
                    <Icon
                      type="edit"
                      className={styles.icon}
                      onClick={event => {
                        edit(event, item);
                      }}
                    />
                  </Tooltip>
                  <Tooltip title="删除">
                    <Icon
                      type="delete"
                      className={styles.icon}
                      onClick={event => {
                        removeTree(event, item);
                      }}
                    />
                  </Tooltip>
                </span>
              ) : null}
            </span>
          );
        } else {
          /* eslint-disable */
          title = (
            <span>
              {index > -1 ? (
                <span>
                  {beforeStr}
                  <span style={{ color: '#f50' }}>{searchValue}</span>
                  {afterStr}
                </span>
              ) : (
                <span>{item.name}</span>
              )}

              {item.processType === '1000' && item.pid === -1 ? (
                <span className={styles.menu_tree_edit}>
                  <Tooltip title="配置">
                    <Icon
                      type="setting"
                      className={styles.icon}
                      onClick={event => {
                        // edit(event, item);
                        props.goToStep(2, { type: 'config', queryTreeData });
                      }}
                    />
                  </Tooltip>
                </span>
              ) : null}
              {item.processType === '1100' ? (
                <span className={styles.menu_tree_edit}>
                  {item.pid !== -1 ? (
                    <Tooltip title="编辑">
                      <Icon
                        type="edit"
                        className={styles.icon}
                        onClick={event => {
                          edit(event, item);
                        }}
                      />
                    </Tooltip>
                  ) : null}
                  <Tooltip title="新增">
                    <Icon
                      type="plus-circle"
                      className={styles.icon}
                      onClick={event => {
                        setTrueFlow();
                        setCatalogPassData(item);
                      }}
                    />
                  </Tooltip>
                  {item.children === null || item.children.length === 0 ? (
                    item.pid !== -1 ? (
                      <Tooltip title="删除">
                        <Icon
                          type="delete"
                          className={styles.icon}
                          onClick={event => {
                            removeTree(event, item);
                          }}
                        />
                      </Tooltip>
                    ) : null
                  ) : null}
                </span>
              ) : null}
            </span>
          );
          /* eslint-enable */
        }
        return (
          <TreeNode
            icon={({ expanded }) => (
              /* eslint-disable */
              <Icon
                type={
                  expanded
                    ? 'folder-open'
                    : item.leaf
                    ? item.processType === '1000'
                      ? 'underline'
                      : 'apartment'
                    : 'folder'
                }
              />
              /* eslint-enable */
            )}
            title={title}
            key={`${item.treeId},${item.processType}`}
            isLeaf={item.leaf ? true : false}
            // 往组织树挂一个detaRef 可供外部获取选中的整个对象数据
            dataRef={item}
          >
            {renderTreeNode(item.children)}
          </TreeNode>
        );
      });
    }
  };

  const onSearch = value => {
    // 为空搜索
    if (!value) {
      setExpandedKeys([]);
      setAutoExpandParent(false);
      setSearchValue('');
      return;
    }
    // 当前选中项的父节点
    setLoading(true);
    request('pmc/pms/PmPackageCatalogController/queryParentIdList', {
      data: {
        catalogName: value,
      },
    })
      .then(res => {
        if (res.success) {
          setExpandedKeys(res.data);
          setAutoExpandParent(true);
          setSearchValue(value);
        } else {
          message.error(res.errMessage);
        }
      })
      .always(() => {
        setLoading(false);
      });
  };

  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  const callBack = value => {
    if (value) {
      queryTreeData();
    }
  };

  return (
    <div className={styles.menu}>
      <div className={styles.menu_search}>
        <Search style={{ marginBottom: 8 }} placeholder="搜索关键字" onSearch={onSearch} />
      </div>
      <ScrollBar autoHide autoHeight autoHeightMax={props.height - 100}>
        <Spin spinning={loading}>
          {TreeData.length > 0 ? (
            <Tree
              showIcon
              expandAction="false"
              className={styles.menu_tree}
              onSelect={selectTreeNode}
              selectedKeys={selectedKeysArr}
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
            >
              {renderTreeNode(TreeData)}
            </Tree>
          ) : (
            <Empty />
          )}
        </Spin>
      </ScrollBar>

      {catalogVisiable ? (
        <Catalog
          title={catalogStatus}
          close={() => {
            setcatalogVisiable(false);
          }}
          visiable={catalogVisiable}
          passdata={catalogPassData}
          callback={callBack}
        />
      ) : null}
      {statusFlow ? (
        <EditStatusFlow
          title={statusFlowType}
          close={() => {
            setStatusFlow(false);
          }}
          visiable={statusFlow}
          passdata={catalogPassData}
          callback={callBack}
        />
      ) : null}
      <Modal
        title="新建状态机"
        width="450px"
        destroyOnClose
        onCancel={setFalseFlow}
        visible={flowStatus}
        footer={null}
      >
        <div className={styles.cata_title}>请选择要新建的类型</div>
        <Button
          size="large"
          block
          type="primary"
          disabled={catalogPassData.pid === -1 ? true : false}
          onClick={() => {
            setFalseFlow();
            setStatusFlow(true);
            setStatusFlowType('add');
            // props.goToStep(3, { obj: { ...catalogPassData, operType: 'add' } });
            // props.goToStep(5, { obj: { ...catalogPassData, operType: 'add' } });
          }}
        >
          + 状态机流程
        </Button>
        <div className={styles.cata_item}>支持简易流程创建。</div>
        <Button
          size="large"
          block
          type="primary"
          ghost
          onClick={() => {
            setFalseFlow();
            setcatalogVisiable(true);
            setCatalogStatus('add');
          }}
        >
          + 状态机目录
        </Button>
        <div className={styles.cata_item}>支持简易子目录创建。</div>
        <Button
          size="large"
          block
          type="primary"
          disabled={catalogPassData.pid === -1 ? true : false}
          ghost
          onClick={() => {
            setFalseFlow();
            setStatusFlow(true);
            setStatusFlowType('export');
          }}
        >
          + 流程导入
        </Button>
      </Modal>
    </div>
  );
}

export default connect(() => ({}))(TreeMenu);
